// YahooRoster_matchups.js - (c) Glenn Carr
//
spaces = "                                                                                                    ";
Matchups = {
    init: function()
    {
        var clipStrings = new Array();
        for ( var iTable = 0; ; iTable++ )
        {
            var statTable = document.getElementById('statTable' + iTable);
            if ( statTable == null )
                break;
                
            var posListed = false;
            var playerType = '';
            var positions = new Object();
            var statGroups = new Array();
            var statHeaders = new Array();
            var playerStats = new Object()
            
            for ( var iRow = 0; iRow < statTable.rows.length; iRow++ )
            {
                var row = statTable.rows[ iRow ];
                var rowClass = getClassName( row );
                if ( rowClass == 'headerRow0' )
                {
                    for ( var iCell = 0; iCell < row.cells.length; iCell++ )
                    {
                        var cell = row.cells[ iCell ];
                        var cellClass = getClassName( cell );
                        if ( /^group/i.test( cellClass ) )
                        {
                            var statGroup = stripTags( cell.innerHTML );
                            statGroups.push( { name:statGroup, count:cell.getAttribute("colspan") } );
                        }
                    }                   
                }
                else if ( rowClass == 'headerRow1' )
                {
                    var iStatGroup = 0;
                    for ( var iCell = 0; iCell < row.cells.length; iCell++ )
                    {
                        var cell = row.cells[ iCell ];
                        var cellClass = getClassName( cell );
                        if ( /^player/.test( cellClass ) )
                        {
                            playerType = stripTags( cell.innerHTML );
                        }
                        else if ( /^stat/.test( cellClass ) )
                        {
                            var statHeader = stripTags( cell.innerHTML );
                            statHeaders.push( statHeader );
                        }
                    }                   
                }
                else if ( /^(odd|even)/i.test( rowClass ) )
                {
                    if ( playerType == 'Batters' )
                    {
                        var player = { name:'', pos:'', stats:new Array() };
                        for ( var iCell = 0; iCell < row.cells.length; iCell++ )
                        {
                            var cell = row.cells[ iCell ];
                            var cellClass = getClassName( cell );
                            if ( /^pos/i.test( cellClass ) )
                            {
                                var playerPos = stripTags( cell.innerHTML );
                                player.pos = playerPos;
                                posListed = true;
                            }
                            else if ( /^player/i.test( cellClass ) )
                            {
                                var a = cell.getElementsByTagName( 'A' );
                                if ( a.length == 0 ) // empty player slot
                                    break;
                                var playerURL = a[ 0 ].getAttribute( 'href' );
                                var playerName = stripAccent( stripTags( cell.innerHTML ) ).replace( /\r\n|^\s+|\s+$/gi, '' ).replace( /\s+/g, ' ' );
                                player.name = playerName;
                            }
                            else if ( /^opp/i.test( cellClass ) )
                            {
                                var playerIsAway = /@/i.test( stripTags( cell.innerHTML ) );
                            }
                            else if ( /^gametime/i.test( cellClass ) )
                            {
                                var gameTime = stripTags( cell.innerHTML ).replace( /^\s+|\s+$/gi, '' );
                                gameTime = gameTime.replace( /\/boxscore/g, '/preview' );
                                //if ( /^\d+\:\d+/i.test( gameTime ) ) // game hasn't been started yet.
                                if ( gameTime != '' )
                                {
                                    var matchup = cell.getElementsByTagName('SPAN');
                                    if ( matchup.length == 0 )
                                    {
                                        matchup = document.createElement( 'SPAN' );
                                        cell.appendChild( matchup );
                                    }
                                    else
                                        matchup = matchup[ 0 ];

                                    var a = cell.getElementsByTagName('A');
                                    if ( a != null && a.length > 0 )
                                    {
                                        matchup.innerHTML = '&nbsp;<span style="color: #cccccc; font-style: italic">[Retrieving starter info..]</span>'
                                        var href = a[ 0 ].getAttribute( 'href' );
                                        href = href.replace( /\/recap|\/boxscore/i, "/preview" );
                                        if ( /preview/i.test( href ) )
                                        {
                                            var req = newXMLHttpRequest();
                                            var handler = getGameInfoReadyStateHandler( req, handleMatchup, matchup, playerIsAway, playerURL );
                                            req.onreadystatechange = handler;
                                            req.open( "GET", href, true );
                                            req.send(null);
                                            //return;
                                        }                                   
                                    }
                                }
                            }
                        }
                    }
                    else if ( playerType == 'Pitchers' )
                    {
                        for ( var iCell = 0; iCell < row.cells.length; iCell++ )
                        {
                            var cell = row.cells[ iCell ];
                            var cellClass = getClassName( cell );
                            if ( /^pos/i.test( cellClass ) )
                            {
                                var playerPos = stripTags( cell.innerHTML );
                                player.pos = playerPos;
                                posListed = true;
                            }
                            else if ( /^player/i.test( cellClass ) )
                            {
                                var a = cell.getElementsByTagName( 'A' );
                                if ( a.length == 0 ) // empty player slot
                                    break;
                                var playerURL = a[ 0 ].getAttribute( 'href' );
                                var playerName = stripAccent( stripTags( cell.innerHTML ) ).replace( /\r\n|^\s+|\s+$/gi, '' ).replace( /\s+/g, ' ' );
                                player.name = playerName;
                            }
                            else if ( /^opp/i.test( cellClass ) )
                            {
                                var _innerText = stripTags( cell.innerHTML );
                                var playerIsAway = /@/i.test( _innerText );
                                var isPitching = /\^/i.test( _innerText );
                                var isPlaying = /^\s*\S+\s*$/i.test( _innerText );
                            }
                            else if ( /^gametime/i.test( cellClass ) )
                            {
                                var matchup = cell.getElementsByTagName('SPAN');
                                if ( matchup.length == 0 )
                                {
                                    matchup = document.createElement( 'SPAN' );
                                    cell.appendChild( matchup );
                                }
                                else
                                    matchup = matchup[ 0 ];
                                matchup.innerHTML = '&nbsp;<span style="color: #cccccc; font-style: italic">[Retrieving team matchup info..]</span>'

                                // Get additional pitcher info
								try {
                                var req = newXMLHttpRequest();
                                var handler = getPitcherMatchupInfoReadyStateHandler( req, handlePitcherMatchupInfo, matchup, isPitching, isPlaying );
                                req.onreadystatechange = handler;
                                req.open( "GET", playerURL, true );
                                req.send(null);
								} catch ( e )
								{
								matchup.innerHTML = '&nbsp;<span style="color: #cccccc; font-style: italic">' + e.description + '</span>'
								}
                            }
                        }
                    }
                } 
            }
        }
    }
};

function handlePitcherMatchupInfo( responseText, el, isPitching, isPlaying )
{
    try {
    var tables = responseText.split( /\<table[^>]+\>|\<\/table\>/i );
    for ( var i = 0; i < tables.length; i++ )
    {
        if ( tables[ i ].match( /Next Game/i ) )
        {
            var table = tables[ i ];
            //var table = table.replace( /(href=\"?)(\/mlb\/players\/\d+)/gi, 'target="sports" $1http://sports.yahoo.com$2' );
            el.innerHTML = '&nbsp;<span style="color: #cccccc; font-style: italic">[Retrieving starter info...]</span><table style="display: none">' + table + '</table>';
            var table = el.getElementsByTagName( 'TABLE' )[ 0 ];
            var matchupInfo = new Array();
			matchupInfo.push( '&nbsp;' );
            var scheduled = false;
            var vs = '';
            for ( var iRow = 0; iRow < table.rows.length; iRow++ )
            {
                var row = table.rows[ iRow ];
                var matches = row.cells[ 0 ].innerHTML.match( /scheduled (next start:\s+\d+\/\d+\s+vs\.\s+([^)]+))/i );
                if ( matches && matches.length > 1 )
                {
                    var matchupHTML = matches[ 1 ].replace( /\<br\>[^<]+$|\<br\>|&nbsp;/gi, '' );
                    if ( isPitching )
                        matchupHTML = matchupHTML.replace( /next start:(.+)$/i, '<b>Starting:$1</b>' );
                    matchupInfo.push( '<span style="color: #000060">' + matchupHTML + '</span>' );
                    scheduled = true;
                    vs = matches[ 2 ];
                }
                else if ( isPlaying && ( matches = row.cells[ 0 ].innerHTML.match( /last game vs\.\s+(\S+)/i ) ) && ( matches.length > 1 ) )
                {
                    if ( vs.length == 0 || teamAbbrsEqual( matches[ 1 ], vs ) )
                    {
                        matchupInfo.push( '<br/>' );
                        matchupInfo.push( '<span style="font-style: italic">' + stripTags( row.cells[ 0 ].innerHTML ) );
                        matchupInfo.push( ': </span>' );
                        getPitcherInfo( row, matchupInfo );
                    }
                }
                else if ( isPlaying && ( matches = row.cells[ 0 ].innerHTML.match( /career vs\.\s+(\S+)/i ) ) && ( matches.length > 1 ) )
                {
                    if ( vs.length == 0 || teamAbbrsEqual( matches[ 1 ], vs ) )
                    {
                        matchupInfo.push( '<br/>' );
                        matchupInfo.push( '<span style="font-style: italic">' + stripTags( row.cells[ 0 ].innerHTML ) );
                        matchupInfo.push( ': </span>' );
                        matchupInfo.push( row.cells[ 1 ].innerHTML );
                        matchupInfo.push( ' G, ' );
                        matchupInfo.push( row.cells[ 2 ].innerHTML );
                        matchupInfo.push( ' GS, ' );
                        getPitcherInfo( row, matchupInfo );
                    }
                }
                else if ( false ) // ( /home|away/i.test( row.cells[ 0 ].innerHTML ) )
                {
                    matchupInfo.push( '<br/>' );
                    matchupInfo.push( '<span style="font-style: italic">' + stripTags( row.cells[ 0 ].innerHTML ) );
                    matchupInfo.push( ': </span>' );
                    matchupInfo.push( row.cells[ 1 ].innerHTML );
                    matchupInfo.push( ' G, ' );
                    matchupInfo.push( row.cells[ 2 ].innerHTML );
                    matchupInfo.push( ' GS, ' );
                    getPitcherInfo( row, matchupInfo );
                }
            }
            var p = getParent( el );
            var append = ( p && /\d+:\d+/i.test( stripTags( p.innerHTML ) ) );
            el.innerHTML = ( append ? ',&nbsp;' : ' ' ) + matchupInfo.join( '' );
            if ( p && isPitching )
                p.innerHTML = '<span style="background: #E0FFFF; padding: 1px 1px">' + p.innerHTML + '</span>';
            return;
        }
    }
    el.innerHTML = '';
    } catch ( e ) 
	{
    	el.innerHTML = '&nbsp;<span style="color: maroon; font-style: italic">' + e.description + '</span>';
	}
}

function getPitcherInfo( row, matchupInfo )
{
    matchupInfo.push( '<nobr>' );
    matchupInfo.push( row.cells[ 3 ].innerHTML + '-' + row.cells[ 4 ].innerHTML );
    matchupInfo.push( '</nobr>, <nobr>' );
    matchupInfo.push( row.cells[ 5 ].innerHTML );
    matchupInfo.push( ' SV</nobr>, <nobr>' );
    matchupInfo.push( row.cells[ 8 ].innerHTML );
    matchupInfo.push( ' IP</nobr>, <nobr>' );
    var era = parseFloat( row.cells[ 15 ].innerHTML );
    if ( era > 5 )
        matchupInfo.push( '<span style="color: red">' + row.cells[ 15 ].innerHTML + '</span>' );
    else if ( era < 3 )
        matchupInfo.push( '<span style="color: green">' + row.cells[ 15 ].innerHTML + '</span>');
    else
        matchupInfo.push( row.cells[ 15 ].innerHTML );
    matchupInfo.push( ' ERA</nobr>, <nobr>' );
    matchupInfo.push( row.cells[ 16 ].innerHTML );
    matchupInfo.push( ' WHIP</nobr>, <nobr>' );
    matchupInfo.push( row.cells[ 17 ].innerHTML );
    matchupInfo.push( ' BAA</nobr>, <nobr>' );
    //matchupInfo.push( row.cells[ 9 ].innerHTML );
    //matchupInfo.push( ' H</nobr>, <nobr>' );
    //matchupInfo.push( row.cells[ 11 ].innerHTML );
    //matchupInfo.push( ' ER</nobr>, <nobr>' );
    matchupInfo.push( row.cells[ 12 ].innerHTML );
    matchupInfo.push( ' HR</nobr>, <nobr>' );
    //matchupInfo.push( row.cells[ 13 ].innerHTML );
    //matchupInfo.push( ' BB</nobr>, <nobr>' );
    matchupInfo.push( row.cells[ 14 ].innerHTML );
    matchupInfo.push( ' K</nobr>' );
}

function handleMatchup( responseText, el, playerIsAway, playerURL )
{
    try
    {
    var tables = responseText.split( /\<table[^>]+\>|\<\/table\>/i );
    for ( var i = 0; i < tables.length; i++ )
    {
        if ( tables[ i ].match( /Starting Pitchers/i ) )
        {
            var table = tables[ i + 1 ];
            var table = table.replace( /(href=\"?)(\/mlb\/players\/\d+)/gi, 'target="sports" $1http://sports.yahoo.com$2' );
            el.innerHTML = '&nbsp;<span style="color: #cccccc; font-style: italic">[Retrieving starter info...]</span><table style="display: none">' + table + '</table>';
            var table = el.getElementsByTagName( 'TABLE' )[ 0 ];
            var pitcherInfo = new Array();
            for ( var iRow = 0; iRow < table.rows.length; iRow++ )
            {
                var row = table.rows[ iRow ];
                if ( /spacer/i.test( row.cells[ 0 ].innerHTML ) )
                    continue;

                var col = ( playerIsAway ? row.cells.length - 1 : 0 );
                if ( /\/mlb\/players/i.test( row.cells[ col ].innerHTML ) )
                {
                    var pitcherHTML = row.cells[ col ].innerHTML.replace( /\<br\>[^<]+$|\<br\>|&nbsp;/gi, '' ).replace( /\<img[^>]+\/?\>/i, '' );
                    pitcherInfo.push( pitcherHTML );
                    var pitcherURL = pitcherHTML.match( /http\:\/\/sports\.yahoo\.com\/mlb\/players\/\d+/i );
                }
                else
                {
                    pitcherInfo.push( stripTags( row.cells[ 1 ].innerHTML.replace( /(rec)ord/i, '$1' ) ) + ' ' + stripTags( row.cells[ col ].innerHTML ) );
                }
            }

            // Get additional pitcher info
            var req = newXMLHttpRequest();
            var handler = getPitcherInfoReadyStateHandler( req, handlePitcherInfo, el, pitcherInfo.join( ', ' ), playerURL );
            req.onreadystatechange = handler;
            req.open( "GET", pitcherURL, true );
            req.send(null);
            return;
        }
    }
    el.innerHTML = '';
    }
    catch ( e ) 
	{
    el.innerHTML = '&nbsp;<span style="color: maroon; font-style: italic">' + e.description + '</span>';
	}
}

function handleBatterInfo( responseText, el, pitcherInfo )
{
	try
	{
    var tables = responseText.split( /\<table[^>]+\>|\<\/table\>/i );
    for ( var i = 0; i < tables.length; i++ )
    {
        if ( tables[ i ].match( /Next Game:/i ) )
        {
            var table = tables[ i ];
            var table = table.replace( /(href=\"?)(\/mlb\/players\/\d+)/gi, 'target="sports" $1http://sports.yahoo.com$2' );
            el.innerHTML = '<table style="display: none">' + table.replace( / height="\d+"/gi, '' ) + '</table>';
            var table = el.getElementsByTagName( 'TABLE' )[ 0 ];
            var pitcherURL = pitcherInfo.match( /\<a href="([^"]+)"/i )[ 1 ];
            var matchupInfo = pitcherInfo;
            for ( var iRow = 0; iRow < table.rows.length; iRow++ )
            {
                var row = table.rows[ iRow ];
                if ( /Career vs \<a href/i.test( row.cells[ 0 ].innerHTML ) )
                {
                    if ( row.cells[ 0 ].innerHTML.toLowerCase().indexOf( pitcherURL.toLowerCase() ) >= 0  ) // If not same pitcher, it's old game info
                    {
                        matchupInfo += '<br/><span style="background: #FFFFE5; padding: 1px 1px">' + row.cells[ 0 ].innerHTML + ': ';
                        var avg = row.cells[ 13 ].innerHTML;
                        var favg = parseFloat( avg );
                        if ( favg >= .3 )
                            avg = '<span style="color: green">' + avg + '</span>'
                        else if ( favg < .2 )
                            avg = '<span style="color: red">' + avg + '</span>'
						var ops = row.cells[ 16 ].innerHTML;
                        matchupInfo += avg + ' (' + row.cells[ 4 ].innerHTML + '/' + row.cells[ 2 ].innerHTML + '), ' + ops + ' OPS, ' + row.cells[ 7 ].innerHTML + ' HR, ' + row.cells[ 8 ].innerHTML + ' RBI, ' + row.cells[ 9 ].innerHTML + ' BB, ' + row.cells[ 10 ].innerHTML + ' K, ' + row.cells[ 11 ].innerHTML + ' SB, ' + row.cells[ 12 ].innerHTML + ' CS';
                        matchupInfo = matchupInfo.replace( /&nbsp;/gi, '' ) + '</span>';
                    }
                    break;
                }
            }
            el.innerHTML = matchupInfo;
            return;
        }
    }
	}
	catch ( e )
	{
    	el.innerHTML = '&nbsp;<span style="color: maroon; font-style: italic">' + e.description + '</span>';
	}
}

function handlePitcherInfo( responseText, el, pitcherInfo, batterURL )
{
	try
	{
        var throws = responseText.match( /Throws:\s+([RL])\<br/ );
    	if ( throws )
    	{
            // Get batter matchup info
            var req = newXMLHttpRequest();
            var handler = getBatterInfoReadyStateHandler( req, handleBatterInfo, el, ', SP: ' + throws[ 1 ] + 'HP ' + pitcherInfo );
            req.onreadystatechange = handler;
            req.open( "GET", batterURL, true );
            req.send(null);
		}
		else
        	el.innerHTML = '';
	}
	catch ( e )
	{
    	el.innerHTML = '&nbsp;<span style="color: maroon; font-style: italic">' + e.description + '</span>';
	}
}

function getPitcherMatchupInfoReadyStateHandler( req, responseHandler, el, isPitching, isPlaying )
{
    return function () {
    if (req.readyState == 4) {
        if (req.status == 200)
            responseHandler( req.responseText, el, isPitching, isPlaying );
        }
    }
}

function getBatterInfoReadyStateHandler(req, responseHandler, el, pitcherInfo, batterURL) {
    return function () {
    if (req.readyState == 4) {
        if (req.status == 200)
            responseHandler( req.responseText, el, pitcherInfo, batterURL );
        }
    }
}

function getPitcherInfoReadyStateHandler(req, responseHandler, el, pitcherInfo, batterURL) {
    return function () {
    if (req.readyState == 4) {
        if (req.status == 200)
            responseHandler( req.responseText, el, pitcherInfo, batterURL );
        }
    }
}

function getGameInfoReadyStateHandler(req, responseHandler, el, playerIsAway, playerURL) {
    return function () {
    if (req.readyState == 4) {
        if (req.status == 200)
            responseHandler( req.responseText, el, playerIsAway, playerURL );
        }
    }
}

function newXMLHttpRequest() {
    var xmlreq = false;
    if (window.XMLHttpRequest) {
        try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch ( e ) { }
        xmlreq = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
            // Try ActiveX
        try { 
            xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) { 
            // first method failed 
            try {
                xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
                 // both methods failed 
            } 
        }
    }
    return xmlreq;
} 

function hilite( s )
{
    return s; // return '<span style="background: yellow; font-weight: bold">' + s + '</span>';
}

function rand(num1, num2)
{
    num1 = parseInt(num1);
    num2 = parseInt(num2);
    return Math.round(num1+Math.random()*(num2-num1));
}

function stripTags(s)
{
    return s.replace(/<\/?[^>]+>|&nbsp;/gi,'');
}

/* Based on code by (C)Stephen Chalmers
* Strips grave, acute & circumflex accents
* http://www.thescripts.com/forum/thread145532.html
*/
function stripAccent(str)
{
    var s=str;

    var rExps=[ 
    /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
    /[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
    /[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
    /[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
    /[\xD9-\xDB]/g, /[\xF9-\xFB]/g, 
    /[\xD1]/g, /[\xF1]/g ];

    var repChar=['A','a','E','e','I','i','O','o','U','u','N','n'];

    for(var i=0; i<rExps.length; i++)
        s=s.replace(rExps[i],repChar[i]);

    return s;
}

function getClassName( el )
{
    var className = el.getAttribute( 'class' );
    if ( className == null )
        className = el.getAttribute( 'className' );
    return className;
}

function getParent( el )
{
    if ( el.parentNode )
        return el.parentNode;
    if ( el.parentElement )
        return el.parentElement;
    return  null;
}

teamAbbrs = new Object();
teamAbbrs[ 'tb' ] = 'tam';
teamAbbrs[ 'kc' ] = 'kan';
teamAbbrs[ 'sf' ] = 'sfo';
function teamAbbrsEqual( a, b )
{   
    a = a.toLowerCase();
    b = b.toLowerCase();
    if ( teamAbbrs.hasOwnProperty( a ) )
        a = teamAbbrs[ a ];
    if ( teamAbbrs.hasOwnProperty( b ) )
        b = teamAbbrs[ b ];
    return a == b;
}

Matchups.init();
